package com.house365.core.application;

import java.util.List;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
import android.util.DisplayMetrics;
import android.view.WindowManager;

import com.baidu.mapapi.SDKInitializer;
import com.house365.androidpn.client.dto.NotificationData;
import com.house365.app.analyse.AnalyseConfig;
import com.house365.app.analyse.HouseAnalyse;
import com.house365.app.analyse.data.AnalyseMetaData;
import com.house365.core.action.ActionTag;
import com.house365.core.bean.NotificationDataRec;
import com.house365.core.constant.CorePreferences;
import com.house365.core.error.CrashHandler;
import com.house365.core.http.BaseHttpAPI;
import com.house365.core.json.JSONException;
import com.house365.core.reflect.ReflectException;
import com.house365.core.security.SecurityFunction;
import com.house365.core.util.DeviceUtil;
import com.house365.core.util.FileUtil;
import com.house365.core.util.PackageUtil;
import com.house365.core.util.appoptimizer.MemoryOptimizer;
import com.house365.core.util.store.BaseDiskCache;
import com.house365.core.util.store.CacheDBService;
import com.house365.core.util.store.DiskCache;
import com.house365.core.util.store.NullDiskCache;
import com.house365.core.util.store.SharedPreferencesUtil;

/**
 * @author py
 * @date 2012-7-5
 * @comment
 */
public abstract class BaseApplication<T extends BaseHttpAPI> extends
		Application {
	protected SharedPreferencesUtil sharedPrefsUtil;
	private SharedPreferences mPrefs;
	protected DisplayMetrics metrics;
	protected float density;
	protected DiskCache diskcache;
	protected T api;
	protected Location location;
	private int screenWidth;
	private int screenHeight;
	private String deviceId;
	public CorePreferences AppCore;
	private final String KEY_ENABLE_IMG="KEY_ENABLE_IMG";
	private final String KEY_FIRST_USE = "KEY_FIRST_USE";
	private final String KEY_ENABLE_PUSH_NOTIFICATION="KEY_ENABLE_PUSH_NOTIFICATION";
	private String version;
	
	public final int CACHE_MAX_SIZE = 50;
	// 推送记录
//	private static final String PREFERENCE_NOTIFICATION_DATA_REC = "notification_data_record_";
//	private String notification_record_suffix="";
		
	private String digest;
	public void onCreate() {
		super.onCreate();
		AppCore = CorePreferences.getInstance(this);

		CrashHandler crashHandler = CrashHandler.getInstance();
		crashHandler.init(getApplicationContext());
		new MemoryOptimizer().optimize();
		sharedPrefsUtil = new SharedPreferencesUtil(this);
		mPrefs = sharedPrefsUtil.getSharedPreferences();
		if (FileUtil.isSDCARDMounted()) {
			diskcache = new BaseDiskCache(AppCore.getCoreConfig().getAppTag(),
					CorePreferences.CACHEPATH);
		} 
		else {
			diskcache = new BaseDiskCache(getCacheDir().getPath(),
					CorePreferences.CACHEPATH);
		}
		if(!diskcache.aviable()){
			diskcache = new NullDiskCache();
		}
		
		setDeviceId(DeviceUtil.getDeviceId(this));
		setVersion(PackageUtil.getVersion(this));
		//@Modify by Rick
		digest = new SecurityFunction().getDevDigest(this);
		api = instanceApi();
		initWindow();
		
		// Init baidu map sdk
		SDKInitializer.initialize(getApplicationContext());
		
		if (CorePreferences.getInstance(this).getCoreConfig().isAnalyse()) {
			HouseAnalyse.setInitConfig(new AnalyseConfig(CorePreferences
					.getInstance(this).getCoreConfig().getAnalyseUrl(),
					metrics, CorePreferences.getInstance(this).getCoreConfig()
							.getAppName(), CorePreferences.getInstance(this)
							.getCoreConfig().getAnalyseBufferSize(),
					CorePreferences.getInstance(this).getCoreConfig()
							.getAnalyseChannel()));
			analyseMetaData = HouseAnalyse.onAppStart(this);
			
			new Thread() {
				public void run() {
					HouseAnalyse.flush();
				}
			}.start();
		}
		
		ActionTag.initTags(AppCore.getCoreConfig().getAppTag());
		
		onAppCreate();
	}

	public CacheDBService getCacheService() {
		return CacheDBService.getInstance(this) ;
	}
	
	protected abstract void onAppCreate();
	protected abstract void onAppDestory();
	public abstract void onAppCancel();

	public String getDeviceId() {
		return deviceId;
	}

	public void setDeviceId(String deviceId) {
		this.deviceId = deviceId;
	}

	public Location getLocation() {
		return location;
	}

	public void setLocation(Location location) {
		this.location = location;
	}

	
	public String getVersion() {
		return version;
	}

	public void setVersion(String version) {
		this.version = version;
	}

	public void initWindow() {
		WindowManager wm = (WindowManager) getApplicationContext()
				.getSystemService(Context.WINDOW_SERVICE);
		screenWidth = wm.getDefaultDisplay().getWidth();
		screenHeight = wm.getDefaultDisplay().getHeight();
		DisplayMetrics dm = new DisplayMetrics();
		wm.getDefaultDisplay().getMetrics(dm);
		setMetrics(dm);
		setDensity(dm.density);
	}

	public SharedPreferencesUtil getSharedPrefsUtil() {
		return sharedPrefsUtil;
	}

	public int getScreenWidth() {
		return screenWidth;
	}
	public int getScreenHeight() {
		return screenHeight;
	}

	protected abstract T instanceApi();

	public DiskCache getDiskCache() {
		return diskcache;
	}

	public SharedPreferences getSharedPreferences() {
		return mPrefs;
	}

	public void setDensity(float density) {
		this.density = density;
	}

	public float getDensity() {
		return density;
	}

	public T getApi() {
		return api;
	}

	public DisplayMetrics getMetrics() {
		return metrics;
	}

	public void setMetrics(DisplayMetrics metrics) {
		this.metrics = metrics;
	}
	
	public void cleanAllFile(){
		try{
			FileUtil.delAllFile(AppCore.getAppTmpSDPath());
			FileUtil.delAllFile(AppCore.getAppDownloadSDPath());
			FileUtil.delAllFile(AppCore.getAppImageSDPath());
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	/**是否启动图片模式**/
	public void enableImg(boolean enable){
		sharedPrefsUtil.putBoolean(KEY_ENABLE_IMG,enable);
	}

	public boolean isEnableImg(){
		return sharedPrefsUtil.getBoolean(KEY_ENABLE_IMG,true);
	}
	/**是否第一次使用该客户端**/
	public void setIsFirst(boolean first){
		sharedPrefsUtil.putBoolean(KEY_FIRST_USE,first);
	}

	public boolean isFirst(){
		return sharedPrefsUtil.getBoolean(KEY_FIRST_USE,true);
	}
	
	/**該版本是否第一次使用**/
	public void setIsFirstVersion(boolean first){
		String  versionName = PackageUtil.getVersion(this);
		sharedPrefsUtil.putBoolean(KEY_FIRST_USE+versionName,first);
	}

	public boolean isFirstVersion(){
		String  versionName = PackageUtil.getVersion(this);
		return sharedPrefsUtil.getBoolean(KEY_FIRST_USE+versionName,true);
	}
	/**是否启动推送服务**/
	public void enablePushNotification(boolean enable){
		sharedPrefsUtil.putBoolean(KEY_ENABLE_PUSH_NOTIFICATION,enable);
	}

	public boolean isEnablePushNotification(){
		return sharedPrefsUtil.getBoolean(KEY_ENABLE_PUSH_NOTIFICATION,true);
	}
	private AnalyseMetaData analyseMetaData;

	
	@Override
	public void onTerminate() {
		super.onTerminate();
		if (CorePreferences.getInstance(this).getCoreConfig().isAnalyse()) {
			new Thread() {
				public void run() {
					if (analyseMetaData != null) {
						HouseAnalyse.onAppDestory(BaseApplication.this,analyseMetaData);
					}
					HouseAnalyse.flush();
				}
			}.start();
		}
		onAppDestory();
	}
	
	public AnalyseMetaData getAnalyseMetaData() {
		return analyseMetaData;
	}
	/**
	 * 子类中实现该方法，获取当前城市的中文名，比如南京
	 * @return
	 */
	public  abstract  String getCityName();

	public String getDigest() {
		return digest;
	}

	public void setDigest(String digest) {
		this.digest = digest;
	}

//	public void setNotification_record_suffix(String notification_record_suffix) {
//		this.notification_record_suffix = notification_record_suffix;
//	}

	/////////////////////////////////////////////////
////
////     推送记录 start
////
////////////////////////////////////////////////
	//推送消息单独放在一张表中与其他缓存分开
	public boolean hasNotificationDataRecRec(NotificationDataRec o) {
//		return getCacheService().hasListItem(PREFERENCE_NOTIFICATION_DATA_REC
//				+ notification_record_suffix, o);
	    if (getCacheService().getPushCache(o.getId(), getCityName()) != null) {
            return true;
        }
	    return false;
	}
	/** 推送消息是否已读*/
	public boolean isNotificationAlreadyRead(NotificationDataRec o) {
	    if (o == null) {
            return false;
        }
	    return isNotificationAlreadyRead(o.getId());
	}
	
	/** 推送消息是否已读*/
	public boolean isNotificationAlreadyRead(String id) {
        if (id == null) {
            return false;
        }
        return getCacheService().isNotificationAlreadyRead(id, getCityName());
    }
	
	/** 标记消息已读*/
	public void markNotificationIsAlreadyRead(NotificationDataRec o) {
	    if (o == null) {
            return;
        }
	    o.setAlreadyRead(1);
	    markNotificationIsAlreadyRead(o.getId());
	}
	
	/** 标记消息已读*/
	public void markNotificationIsAlreadyRead(String id) {
        if (id == null) {
            return;
        }
        getCacheService().markNotificationIsAlreadyRead(id, getCityName());
    }
	
    /**
     * 添加消息
     * <p> 如果消息的id和原来添加的id重复，就将原来的删除，重新添加
     * @param o 消息
     */
    public void addNotificationDataRecRec(NotificationDataRec o) {
        if (o == null) {
            return;
        }
        o.setCity(getCityName());
        // 如果已经添加过了
        // 删除重加
        if (hasNotificationDataRecRec(o)) {
            removeNotificationDataRecRec(o);
        }
        getCacheService().addPushCache(o.getContentValues());
    }
    /**
     * 添加消息
     * <p> 如果消息的id和原来添加的id重复，就将原来的删除，重新添加
     * <p> 因为NotificationData没有city字段，所以数据库中的city字段将会
     *     被设置成应用所设置的城市
     * @param data 消息
     */
    public void addNotificationDataRecRec(NotificationData data) {
        if (data == null) {
            return;
        }
        NotificationDataRec dataRec = new NotificationDataRec(data, getCityName());
        // 如果已经添加过了
        // 删除重加
        if (hasNotificationDataRecRec(dataRec)) {
            removeNotificationDataRecRec(dataRec);
        }
        getCacheService().addPushCache(dataRec.getContentValues());
    }
    
    public void removeNotificationDataRecRec(NotificationDataRec o) {
        if (o == null) {
            return;
        }
        getCacheService().deletePushCache(o.getId(), getCityName());
    }
    /** 
     * 测试使用 
     * <p>向数据库中添加数据*/
    @SuppressWarnings("unused")
    private void addData() {
        NotificationDataRec dataRec = null;
        for (int i = 1001; i < 1010; i++) {
            dataRec = new NotificationDataRec("" + i, "title", "message", "uri", 0, "nanjing");
            addNotificationDataRecRec(dataRec);
        }
    }
    public List<NotificationDataRec> queryNotificationDataRec()
            throws ReflectException, JSONException {
        getCacheService().deleteOutOfDatePushCache();
        return getCacheService().getAllPushCache(getCityName());
    }
    /** 当天推送消息中是否存在没有被读过的消息**/
    public boolean isExistNewPushNotification() {
        getCacheService().deleteOutOfDatePushCache();
        List<NotificationDataRec> list = getCacheService().getCurrentDatePushCache(getCityName());
        for (NotificationDataRec notificationDataRec : list) {
            if (notificationDataRec.getAlreadyRead() == 0) {
                //存在新的的推送消息（没有被读过）
                return true;
            }
        }
        return false;
    }

//	public void addNotificationDataRecRec(NotificationDataRec o) {
//		if (hasNotificationDataRecRec(o)) {
//			// 已经添加过了
//			// 加过删除重加
//			removeNotificationDataRecRec(o);
//		}
//		List<NotificationDataRec> records = null;
//		int r_count = 0;
//		try {
//			records = queryNotificationDataRec();
//			r_count = records.size();
//		} catch (ReflectException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (JSONException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		if (r_count >= CACHE_MAX_SIZE) {
//			getCacheService().removeListItem(PREFERENCE_NOTIFICATION_DATA_REC
//					+ notification_record_suffix, records.get(0));
//		}
//		getCacheService().addListItem(PREFERENCE_NOTIFICATION_DATA_REC
//				+ notification_record_suffix, o);
//	}
//
//	public void removeNotificationDataRecRec(NotificationDataRec o) {
//		getCacheService().removeListItem(PREFERENCE_NOTIFICATION_DATA_REC
//				+ notification_record_suffix, o);
//	}
//
//	public List<NotificationDataRec> queryNotificationDataRec()
//			throws ReflectException, JSONException {
//		List<NotificationDataRec> notiRec = new ArrayList<NotificationDataRec>();
//		notiRec = getCacheService().getListWithCast(new NotificationDataRec(),
//				PREFERENCE_NOTIFICATION_DATA_REC + notification_record_suffix);
//		Collections.reverse(notiRec);
//		return notiRec;
//	}
/////////////////////////////////////////////////
////
////推送记录 end
////
////////////////////////////////////////////////
	
}
